﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StockCommon;
using StockCommon.data;

namespace StockPostProcessLib
{
    public class UpDownProcessor
    {
        protected DateTime processFrom(String code, DateTime fromDay)
        {
            StockDataClassesDataContext context = LinqAgent.getContext();
            List<StockDaily> records = (from r in context.StockDailies where (r.證券代號 == code && r.日期 >= fromDay) orderby r.日期 select r).ToList<StockDaily>();

            int sz = records.Count;
            if (sz <= 1)
                return fromDay;

            decimal? lastprice = null;
            lastprice = records[0].開盤價;

            int starti = 0;
            if (lastprice == null)
                for (int i = 0; i < sz; i++)
                {
                    if (records[i].開盤價 != null)
                    {
                        lastprice = records[i].開盤價;
                        starti = i; break;
                    }
                }
            for (int i = starti; i < sz; i++)
            {
                decimal? curv = records[i].收盤價;
                if (curv == null)
                    continue;
                if (records[i].漲跌價差 == null)
                    records[i].漲跌價差 = curv - lastprice;
                lastprice = curv;
            }
            return records[sz - 1].日期;
        }
        public void process()
        {
            StockDataClassesDataContext context = LinqAgent.getContext();
            DateTime minDay, maxDay;
            StockDataModule.getMinMaxDate("", out minDay, out maxDay);
            List<String> codes = StockManager.getRecentValidStockCodes();

            Dictionary<String, PostProcessLog> processlogs = (from ll in context.PostProcessLogs select ll).ToDictionary(k => k.stockCode);

            foreach (String code in codes)
            {
                DateTime? from = null;
                if (processlogs.ContainsKey(code))
                    from = processlogs[code].漲跌計算;
                if (from == null)
                    from = minDay;
                DateTime to = processFrom(code, (DateTime)from);
                if (to.Equals(from))
                    continue;

                if (processlogs.ContainsKey(code))
                {
                    processlogs[code].漲跌計算 = to;
                }
                else
                {
                    PostProcessLog record = new PostProcessLog();
                    record.stockCode = code;
                    record.漲跌計算 = to;
                    context.PostProcessLogs.InsertOnSubmit(record);
                }
                //因為要算很久~~,所以每次立刻submit
                context.SubmitChanges();
            }
            codes.Clear();
            processlogs.Clear();
        }
    }
}
